package com.mk.legoscans2;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Random;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Utils {

	public static Bitmap getImageBitmapFromUrl(URL url)
	{
		try {
			return BitmapFactory.decodeStream((InputStream)url.getContent());
		} catch (IOException e) {
			return null;
		}
	}
	
	public static boolean isNetworkAvailable(Context context) {
	    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
	
	public static String getThumbnailUrl(String scanId)
	{
		return "http://api.legoscans.com/image/" + scanId + "/0?source=android";
	}
	
	public static String getUrlSafeTheme(String theme)
	{
		return theme
			.replace("$", "")
			.replace("&", "")
			.replace("+", "")
			.replace(",", "")
			.replace("/", "")
			.replace(":", "")
			.replace(";", "")
			.replace("=", "")
			.replace("?", "")
			.replace("@", "");
	}
	
	public static String getLocalStorageFolderName(Scan scan)
	{
		String folderName = scan._scanId + "_" + scan._name.replace(" ", "");
		return getValidFolderName(folderName);
	}
	
	private static String getValidFolderName(String folderName)
	{
		String fn = "";
		for(int i = 0; i < folderName.length(); i++)
		{
			Character c = folderName.charAt(i);
			if("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789_-".contains(c.toString()))
			{
				fn += c;
			}
		}
		
		if(fn.length() == 0)
		{
			Integer newFolderName = new Random().nextInt(9999999);
			fn = newFolderName.toString();
		}
		
		return fn;
	}
	
	public static float getMb(long bytes)
	{
		float mb = bytes / 1048576f;
		return Math.round(mb * 100f) / 100f;
	}
	
	public static String padLeft(String str, int totalLength, char padChar)
	{
		String padding = "";
		for(int i = 0; i < (totalLength - str.length()); i++)
		{
			padding += padChar;
		}
		return padding + str;
	}
	
	public static String postToWebApi(String path, String query){
		String response = "";
		try {
			URL url;
			try {
				URI uri = new URI("http", null, LegoScans3Application.ApiDomain, LegoScans3Application.ApiPort, path, null, null);
				url = new URL(uri.toASCIIString());
			} catch (URISyntaxException e) {
				throw new RuntimeException(e);
			} catch (MalformedURLException e) {
				throw new RuntimeException(e);
			}
	
			HttpURLConnection con = (HttpURLConnection)url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("Content-length", String.valueOf(query.length())); 
			con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
			con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)"); 
			con.setDoOutput(true); 
			con.setDoInput(true);
			
			DataOutputStream output = new DataOutputStream(con.getOutputStream());
			output.writeBytes(query);
			output.close();
			DataInputStream input = new DataInputStream( con.getInputStream() ); 
	
			
			for( int c = input.read(); c != -1; c = input.read() ) 
				response  += ((char)c); 
			input.close();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return response;
	}
}
